package com.emip.job.method;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.emip.bean.AlterLogBean;
import com.emip.bean.DayStoreBean;
import com.emip.bean.ItemBean;
import com.emip.bean.SiteBean;
import com.emip.bean.SiteItemBean;
import com.emip.bean.WeekStoreBean;
import com.emip.service.DayStoreService;
import com.emip.service.ItemService;
import com.emip.service.SiteService;
import com.emip.service.WeekStoreService;
import com.emip.util.ReportFormat;
import com.emip.util.report.Comput;
import com.emip.util.report.Statistics;

@Component
public class WeekMethod {

	static Logger logger = Logger.getLogger(WeekMethod.class);
	
	@Autowired
	DayStoreService dayStoreService;
	
	@Autowired
	WeekStoreService weekStoreService;
	
	@Autowired
	ItemService itemService;
	
	@Autowired
	SiteService siteService;
	
	public void comput(Calendar calendar, Statistics statistic, String[] items, String siteId) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(ReportFormat.DAYFORMAT);
		Calendar cal = (Calendar) calendar.clone();
		cal.add(Calendar.WEEK_OF_YEAR, -1);
		cal.set(Calendar.DAY_OF_WEEK, 1);
		Date startDate = cal.getTime();
		cal.set(Calendar.DAY_OF_WEEK, 7);
		Date endDate = cal.getTime();
		List<DayStoreBean> stores = dayStoreService.getByTimespan(
				dateFormat.format(startDate), dateFormat.format(endDate), items, siteId);
		logger.info("Report Job, Computing WEEK Data with siteId=" + 
				siteId + " and itemId=" + Arrays.toString(items) + ":" + 
				dateFormat.format(startDate) + "  --  " +
				dateFormat.format(endDate));
		
		String year = cal.get(Calendar.YEAR) + "";
		int weekth = cal.get(Calendar.WEEK_OF_YEAR);
		statistic.init();
		statistic.comput(stores);
		Map<String, Comput> computs = statistic.getResults();
		for (Map.Entry<String, Comput> entry: computs.entrySet()) {
			Comput comput = entry.getValue();
			String[] key = entry.getKey().split("_");
			if (!key[0].equals("AverageComput")) continue;
			WeekStoreBean week = weekStoreService.findByWeekth(year, weekth+"", key[1], key[2]);
			if (week == null) {
				week = new WeekStoreBean();
				week.setWeekth(weekth);
				week.setYear(year);
				
				SiteBean site = siteService.getSiteByID(key[1]);
				week.setSite(site);

				ItemBean item = itemService.getItemByID(key[2]);
				week.setItem(item);
				
				if (item == null || site == null) continue;
			}
			week.setFlag(comput.getFlag());
			String result = null;
			try {
				result = comput.getResult();
			} catch (Exception e) {
				continue;
			}
			if (result == null || comput.getCount() == 0) continue;
			week.setValue(result);

			SiteBean site = siteService.getSiteByID(key[1]);
			week.setSite(site);

			ItemBean item = itemService.getItemByID(key[2]);
			week.setItem(item);
			
			if (item == null || site == null) continue;
			weekStoreService.merge(week);
		}
	}
	
	public static void main(String[] args) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, 2012);
		calendar.set(Calendar.WEEK_OF_YEAR, 53);
		
		calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) + 1);
		calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) + 1);
		calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) + 1);
		
		Calendar cal = (Calendar) calendar.clone();
		cal.add(Calendar.WEEK_OF_YEAR, -1);
		cal.set(Calendar.DAY_OF_WEEK, 1);
		Date startDate = cal.getTime();
		cal.set(Calendar.DAY_OF_WEEK, 7);
		Date endDate = cal.getTime();
		
		
		System.out.println(startDate);
		System.out.println(endDate);
	}
	
	public void doWork(Calendar clone, Statistics statistic) {
		List<SiteItemBean> siteItems = statistic.getSiteItems();
		for (int i = 0; i < siteItems.size(); i++) {
			SiteItemBean siteItem = siteItems.get(i);
			String itemId = siteItem.getItem().getId();
			String siteId = siteItem.getSite().getId();
			String lastDate = weekStoreService.getLastDate(itemId, siteId);
			if (lastDate != null) {
				String[] times = lastDate.split(" ");
				Calendar calendar = Calendar.getInstance();
				calendar.set(Calendar.YEAR, Integer.parseInt(times[0]));
				calendar.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(times[1]) + 1);
				while (calendar.getTimeInMillis() <= clone.getTimeInMillis()) {
					calendar.set(Calendar.WEEK_OF_YEAR, calendar.get(Calendar.WEEK_OF_YEAR) + 1);
					comput(calendar, statistic, new String[]{itemId}, siteId);
				}
			} else {
				comput(clone, statistic, new String[]{itemId}, siteId);
			}
		}
	}
	
	public void statistic(Calendar clone, Statistics statistic) {
		List<SiteItemBean> siteItems = statistic.getSiteItems();
		for (int i = 0; i < siteItems.size(); i++) {
			SiteItemBean siteItem = siteItems.get(i);
			String itemId = siteItem.getItem().getId();
			String siteId = siteItem.getSite().getId();
			comput(clone, statistic, new String[]{itemId}, siteId);
		}
	}
	
	public void merge(AlterLogBean log) {
		String siteId = log.getSite().getId();
		String itemId = log.getItem().getId();
		String date = log.getDate();
		String[] dates = date.split("年|周");
		WeekStoreBean store = 
				weekStoreService.findByWeekth(dates[0], dates[1], siteId, itemId);
		store.setValue(log.getNewvalue());
		weekStoreService.merge(store);
	}
}
